﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
using System.Windows.Forms;

namespace IMLibrary.Controls
{
    /// <summary>
    /// 
    /// </summary>
    public class ListViewSubEx
    {
        //无需改动
        private const int LVM_FIRST = 0x1000;
        private const int LVM_SETEXTENDEDLISTVIEWSTYLE = LVM_FIRST + 54;//
        private const int LVS_EX_SUBITEMIMAGES = 0x0002;
        private const int LVIF_TEXT = 0x0001;
        private const int LVIF_IMAGE = 0x0002;
        private const int LVM_SETITEM = LVM_FIRST + 6;//
        private struct LV_ITEM
        {
            public uint mask;//显示内容？
            public int iItem;//行号
            public int iSubItem;//列号
            public uint state;//状态？
            public uint stateMask;//状态掩码？
            public IntPtr pszText;//文字
            public int cchTextMax;
            public int iImage;//图片索引号
            public IntPtr lParam;
        }

        [DllImport("user32.dll")]
        static extern int SendMessage(IntPtr hwnd, int msg, int wParam, int lParam);
        [DllImport("user32.dll", SetLastError = true)]
        static extern int SendMessage(IntPtr hwnd, int msg, int wParam, ref LV_ITEM lParam);
        
        /// <summary>
        /// 显示图片
        /// </summary>
        /// <param name="listView">listView</param>
        /// <param name="row">行，索引</param>
        /// <param name="col">列，索引</param>
        /// <param name="imageList">图片列表控件</param>
        /// <param name="index">图片索引</param>
        public void ShowImage(ListView listView, int row, int col, ImageList imageList, int index)
        {
            SendMessage(listView.Handle, LVM_SETEXTENDEDLISTVIEWSTYLE, LVS_EX_SUBITEMIMAGES, LVS_EX_SUBITEMIMAGES);//要先加这个，要不然图片暂时显示不出来，得要一个事件来触发
            //显示图片
            LV_ITEM lvitem = new LV_ITEM();//实例化LV_ITEM结构           
            lvitem.mask = LVIF_TEXT | LVIF_IMAGE;//设置显示内容，文本+图片
            lvitem.iItem = row;//设置行号
            lvitem.iSubItem = col;//设置列
            listView.SmallImageList = imageList ;//设置listView的SmallImageList
            lvitem.iImage = index;//设置图片索引
            //和图片一起显示的文字，可以指定，不一定是原来位置的,也可以不启用
            if (listView.Items[row].SubItems[col].Text != null)//不为空，则赋值，使其和图片一起显示出来
            {
                lvitem.pszText = Marshal.StringToHGlobalAnsi(listView.Items[row].SubItems[col].Text);
            }
            SendMessage(listView.Handle, LVM_SETITEM, 0, ref lvitem);//发送，并返回
        }
    }
}
